package com.example.treehole.api;

import android.content.Context;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Api {
    private static OkHttpClient client;
    private static String requestUrl;
    private static HashMap<String,String> mParams;
    private static Api api= new Api();
    private static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");

    private Api(){
    }

    public static Api config(String url, HashMap<String,String> params){
        client = new OkHttpClient.Builder().build();
        requestUrl=url;
        mParams=params;
        return api;
    }

    public void postRequest(Context context,Callback callback){
        //处理参数
        FormBody.Builder builder=new FormBody.Builder();
        for (String key:mParams.keySet())
            builder.add(key, Objects.requireNonNull(mParams.get(key)));
        RequestBody body=builder.build();
        //取出token
        String token=context.getSharedPreferences("treeHole",Context.MODE_PRIVATE).getString("token","");
        //创建request
        Request request=new Request.Builder()
                .url(requestUrl)
                .addHeader("token",token)
                .post(body)
                .build();
        //创建call回调对象
        final Call call=client.newCall(request);
        //发起请求
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
               final String result=response.body().string();
                callback.onSuccess(result);
            }
        });
    }

    public void postFile(Context context,List<File> files, Callback callback) {
        MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (File file:files){
            RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
            requestBody.addFormDataPart("images", file.getName(), body);
        }
        for (String key:mParams.keySet())
            requestBody.addFormDataPart(key, Objects.requireNonNull(mParams.get(key)));
        //取出token
        String token=context.getSharedPreferences("treeHole",Context.MODE_PRIVATE).getString("token","");
        //创建request
        Request request=new Request.Builder()
                .url(requestUrl)
                .addHeader("token",token)
                .post(requestBody.build())
                .build();
        //创建call回调对象
        final Call call=client.newCall(request);
        //发起请求
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result=response.body().string();
                callback.onSuccess(result);
            }
        });

    }

    //异步
    public void getRequest(Context context,Callback callback){
        //拼接参数
        requestUrl=append(requestUrl,mParams);
        //取出token
        String token=context.getSharedPreferences("treeHole",Context.MODE_PRIVATE).getString("token","");
        //创建request
        Request request=new Request.Builder()
                .url(requestUrl)
                .addHeader("contentType","application/json;charset=UTF-8")
                .addHeader("token",token)
                .get()
                .build();
        //创建call回调对象
        final Call call=client.newCall(request);
        //发起请求
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result=response.body().string();
                callback.onSuccess(result);
            }
        });
    }


    //同步
    public String getRequestSync(Context context){
        //拼接参数
        requestUrl=append(requestUrl,mParams);
        //取出token
        String token=context.getSharedPreferences("treeHole",Context.MODE_PRIVATE).getString("token","");
        //创建request
        Request request=new Request.Builder()
                .url(requestUrl)
                .addHeader("contentType","application/json;charset=UTF-8")
                .addHeader("token",token)
                .get()
                .build();
        //创建call回调对象
        final Call call=client.newCall(request);
        //发起请求
        try {
            Response response = call.execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "false";
    }


    private String append(String requestUrl, HashMap<String, String> mParams) {
        StringBuilder urlParams = new StringBuilder(requestUrl).append("?");
        Set<Map.Entry<String, String>> entries = mParams.entrySet();
        for (Map.Entry<String, String> entry : mParams.entrySet()) {
            urlParams.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        String urlParamsStr = urlParams.toString();
        return urlParamsStr.substring(0, urlParamsStr.length()-1);
    }
}
